<!--
 * @Descripttion:
 * @version:
 * @Author: sueRimn
 * @Date: 2020-10-20 17:48:29
 * @LastEditors: sueRimn
 * @LastEditTime: 2020-11-13 16:47:44
-->
<template>
  <div class="app-container">
    <div v-pageRoles="['5fab781ac4830']">
      <div class="screenHeader">
        <div class="searchInput">
          <el-input
            v-model="searchValue"
            size="medium"
            placeholder="请输入问卷名称"
            class="input-with-select"
          >
            <el-button
              slot="append"
              size="medium"
              icon="el-icon-search"
              @click="searchList"
            />
          </el-input>
        </div>
        <div>
          <el-button
            size="medium"
            icon="el-icon-refresh"
            @click="shuaXin"
          >刷新</el-button>
          <el-button
            v-pageRoles="['5fab7808580c0']"
            size="medium"
            type="primary"
            icon="el-icon-plus"
            @click="toAddProject"
          >新增</el-button>
          <el-button
            type="info"
            size="medium"
            icon="el-icon-delete-solid"
            @click="toUrl('/intelligentTest/recycleBin')"
          >回收站</el-button>
        </div>
      </div>
      <el-table
        v-loading="listLoading"
        :data="list"
        element-loading-text="Loading"
        border
        fit
        highlight-current-row
      >
        <el-table-column align="center" label="序号" width="50">
          <template slot-scope="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column label="名称" header-align="center">
          <template slot-scope="scope">
            {{ scope.row.group_name }}
          </template>
        </el-table-column>
        <el-table-column label="类型" width="90" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.type === 1 ? "问卷" : "试题" }}</span>
          </template>
        </el-table-column>
        <el-table-column label="对象" width="90" align="center">
          <template slot-scope="scope">
            {{ scope.row.face === 1 ? "学生" : "家长" }}
          </template>
        </el-table-column>
        <el-table-column
          class-name="status-col"
          label="状态"
          width="90"
          align="center"
        >
          <template slot-scope="scope">
            <el-tag :type="scope.row.status | statusFilter">{{
              scope.row.status === 0 ? "未发布" : "已发布"
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="提供者" width="90" align="center">
          <template slot-scope="scope">
            {{ scope.row.createor_name }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="创建时间" width="220">
          <template slot-scope="scope">
            <i class="el-icon-time" />
            <span>{{ scope.row.create_time }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="最后修改时间" width="220">
          <template slot-scope="scope">
            <i class="el-icon-time" />
            <span>{{ scope.row.update_time }}</span>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="300" align="center">
          <template slot-scope="scope">
            <el-button size="mini" @click="yuLang(scope.row)">预览</el-button>
            <el-button
              v-if="scope.row.status == 0"
              v-pageRoles="['5fab7812f3713']"
              size="mini"
              type="success"
              @click="toEdit(scope.row)"
            >编辑</el-button>
            <el-button
              v-if="scope.row.status == 0"
              v-pageRoles="['5fab7812f3713']"
              size="mini"
              type="primary"
              @click="useGroup(scope.row.unid, scope.$index)"
            >发布</el-button>
            <el-button
              v-if="scope.row.status == 1"
              v-pageRoles="['5fab7812f3713']"
              size="mini"
              type="warning"
              @click="useGroup(scope.row.unid, scope.$index)"
            >取消发布</el-button>
            <el-button
              v-if="scope.row.status == 1"
              size="mini"
              type="primary"
              @click="crateQrcode(scope.row)"
            >分享二维码</el-button>
            <el-button
              v-if="scope.row.status != 1"
              v-pageRoles="['5fab780e77085']"
              size="mini"
              type="danger"
              @click="deleteGroup(scope.row.unid)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="bottomPagination">
        <el-pagination
          :current-page="currentPage"
          :page-sizes="[10, 30, 50]"
          :page-size="pageSize"
          layout=" sizes, prev, pager, next,total, jumper"
          :total="total"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        />
      </div>
      <!-- 弹窗 -->
      <el-dialog
        title="创建新项目"
        :visible.sync="dialogVisible"
        width="30%"
        :before-close="handleClose"
      >
        <el-form ref="form" label-width="100px">
          <el-form-item label="选择模板">
            <el-select v-model="selectTemplate" placeholder="请选择模板">
              <el-option label="空白模板" value="1" />
              <el-option label="组卷模板" value="2" />
            </el-select>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="toAddProject">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 分享二维码 -->
      <el-dialog
        :visible.sync="qrcodeDialogVisible"
        width="375px"
        :before-close="handleClose"
      >
        <el-form>
          <el-form-item label="选择分享模板">
            <el-radio-group v-model="selectShare">
              <el-radio :label="0">模板一</el-radio>
              <el-radio :label="1">模板二</el-radio>
              <el-radio :label="2">模板三</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
        <div
          ref="imageWrapper"
          class="qrcodeBg"
          :style="{ backgroundImage: `url(${muBan[selectShare].url})` }"
        >
          <div :style="{color:(selectShare==0?'#fff':'#000')}" class="yuLanMess">
            <div class="yuLanRow">问卷名：{{ showYuLanMess.groundName }}</div>
            <div class="yuLanRow">对象：{{ showYuLanMess.obj }}</div>
            <div class="yuLanRow">提供人：{{ showYuLanMess.createor_name }}</div>
            <div id="qrcode" ref="qrcode" />
          </div>
          <div class="gongShi" :style="{color:(selectShare==0?'#fff':'#000')}">服务提供商：深圳智助教育科技有限公司</div>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="downQrcode">下载图片</el-button>
          <el-button type="primary" @click="closeQrcode">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 预览 -->
      <el-dialog
        title="预览"
        :visible.sync="yulangDialogVisible"
        width="450px"
        :before-close="handleClose"
        class="noPaddingDialog"
        top="20px"
      >
        <div class="phoneBox">
          <Phone v-if="yulangDialogVisible" :show_url="showUrl" />
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button
            type="primary"
            @click="yulangDialogVisible = false"
          >确 定</el-button>
        </span>
      </el-dialog>
    </div>
    <noRolesTips v-noRolesTips="['5fab781ac4830']" />
  </div>
</template>

<script>
import QRCode from 'qrcodejs2'
import html2canvas from 'html2canvas'
import { getGroup, toRecycleBinFroup, toUseGroup } from '@/api/question'
import { getGroupSingle } from '@/api/paper'
import Phone from '@/components/Phone'
import noRolesTips from '@/components/noRolesTips'
const Global = require('../../../env/index')
export default {
    name: 'IntelligentTest',
    filters: {
        statusFilter(status) {
            const statusMap = ['warning', '']
            return statusMap[status]
        }
    },
    components: {
        Phone,
        noRolesTips
    },
    data() {
        return {
            searchValue: '', // 搜索
            list: [], // 列表
            currentPage: 1, // 页数
            total: 0, // 总数
            pageSize: 10, // 每页条数
            listLoading: true, // table 加载
            dialogVisible: false, // 创建
            selectTemplate: '1', // 1空白模板 2组卷模板
            qrcodeDialogVisible: false, // 二维码
            yulangDialogVisible: false, // 预览
            showUrl: '', // 预览
            showYuLanMess: {
                groundName: '',
                obj: '',
                createor_name: ''
            }, // 预览信息
            selectShare: 0, // 分享模板
            muBan: [
                { url: require('@/assets/qrcodeBg/bg1.png') },
                { url: require('@/assets/qrcodeBg/bg2.png') },
                { url: require('@/assets/qrcodeBg/bg3.png') }
            ]
        }
    },
    created() {
        this.get_QuestionList()
    },
    methods: {
    // 刷新
        shuaXin() {
            this.currentPage = 1
            this.get_QuestionList()
        },
        // 编辑
        toEdit(row) {
            console.log(row)
            getGroupSingle({ unid: row.unid }).then((res) => {
                console.log(res)
                if (res.code == 200) {
                    this.$router.push({
                        path: '/intelligentTest/projectEdit',
                        query: { groundId: row.unid }
                    })
                }
            })
        },
        yuLang(row) {
            this.showUrl = `${Global.ifram_url}?psq_test_id=${row.unid}&link_type=search`
            this.yulangDialogVisible = true
        },
        toUrl(url) {
            this.$router.push(url)
        },
        handleClose(done) {
            done()
        },
        handleCurrentChange(val) {
            this.currentPage = val
            this.get_QuestionList()
        },
        handleSizeChange(val) {
            this.currentPage = 1
            this.pageSize = val
            this.get_QuestionList()
        },
        searchList() {
            this.currentPage = 1
            if (this.searchValue === '') this.get_QuestionList()
            this.listLoading = true
            getGroup({
                limit: this.pageSize,
                page: this.currentPage,
                group_name: this.searchValue
            }).then((res) => {
                if (res.code === 200) {
                    this.list = res.data.list
                    this.total = res.data.total
                }
                this.listLoading = false
            })
        },
        // 获取问卷列表
        get_QuestionList() {
            this.listLoading = true
            getGroup({
                limit: this.pageSize,
                page: this.currentPage
            }).then((res) => {
                if (res.code === 200) {
                    this.list = res.data.list
                    console.log('list', this.list)
                    this.total = res.data.total
                }
                this.listLoading = false
            })
        },
        // 发布/取消发布
        useGroup(unid, index) {
            var data = {
                unid
            }
            if (this.list[index].status === 0) {
                data.status = 1
            }
            toUseGroup(data).then((res) => {
                console.log(res)
                if (res.code === 200) {
                    if (this.list[index].status === 0) {
                        this.list[index].status = 1
                    } else {
                        this.list[index].status = 0
                    }
                    this.$message({
                        type: 'success',
                        customClass: 'customClass',
                        message: '操作成功!'
                    })
                }
            })
        },
        // 二维码
        crateQrcode(row) {
            this.qrcodeDialogVisible = true
            this.showYuLanMess = {
                groundName: row.group_name,
                obj: row.face === 1 ? '学生' : '家长',
                createor_name: row.createor_name
            }

            this.$nextTick(() => {
                var qrcodeUrl = `${Global.ifram_url}?psq_test_id=${row.unid}`
                console.log(qrcodeUrl)

                const qrcodeImgEl = document.getElementById('qrcode')
                qrcodeImgEl.innerHTML = ''
                var qrcode = new QRCode(qrcodeImgEl, {
                    width: 200,
                    height: 200, // 高度
                    text: qrcodeUrl // 二维码内容
                    // render: 'canvas' // 设置渲染方式（有两种方式 table和canvas，默认是canvas）
                    // background: '#f0f'
                    // foreground: '#ff0'
                })
                qrcode.makeCode(qrcodeUrl)
            })
        },
        // 取消二维码
        closeQrcode() {
            this.qrcodeDialogVisible = false
        },
        // 保存二维码
        downQrcode() {
            html2canvas(this.$refs.imageWrapper, {
                backgroundColor: null
            }).then((canvas) => {
                const dataURL = canvas.toDataURL('image/png')
                // this.dataURL = dataURL
                var a = document.createElement('a') // 生成一个a元素
                var event = new MouseEvent('click') // 创建一个单击事件
                a.download = name || 'code' // 设置图片名称
                a.href = dataURL // 将生成的URL设置为a.href属性
                a.dispatchEvent(event)
            })
        },
        // 新增
        toAddProject() {
            //   this.dialogVisible = false
            this.$router.push({
                path: '/intelligentTest/projectAdd',
                query: { selectTemplate: this.selectTemplate }
            })
        },
        // 删除问卷至回收站
        deleteGroup(unid) {
            this.$confirm('此操作将该问卷移至回收站, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            })
                .then(() => {
                    toRecycleBinFroup({
                        unid
                    }).then((res) => {
                        console.log('====================================')
                        console.log('删除', res)
                        console.log('====================================')
                        if (res.code === 200) {
                            this.$message({
                                type: 'success',
                                customClass: 'customClass',
                                message: '删除成功!'
                            })
                            this.get_QuestionList()
                        }
                    })
                })
                .catch(() => {})
        }
    }
}
</script>

<style scoped lang="scss">
.screenHeader {
  width: 100%;
  margin: 15px 0;
  display: flex;
  justify-content: space-between;

  .searchInput {
    width: 300px;
  }
}

.bottomPagination {
  padding: 15px 0;
}

.radioRow {
  width: 100%;
  display: flex;
  justify-content: space-around;
  margin-top: 20px;
}

.qrcodeBg {
  width: 100%;
  height: 400px;
  display: flex;
  justify-content: center;
  align-items: center;
  background-repeat: no-repeat;
  background-size: 100% 100%;
  position: relative;
}

.phoneBox {
  width: 100%;
  display: flex;
  justify-content: center;
}

.yuLanMess {
    .yuLanRow {
        margin-bottom: 8px;
        width: 200px;
        line-height: 20px;
    }
}

.gongShi{
    position: absolute;
    bottom: 10px;
    right: 15px;
    color: #000;
    font-size: 12px;
}
</style>
